package com.dong.pattern;

import javax.security.auth.Subject;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 1. 类: {@link java.lang.reflect.Proxy}
 *  接口: {@link java.lang.reflect.InvocationHandler}
 *   只能基于接口进行动态代理
 */
public class JdkProxySubject implements InvocationHandler {
    public JdkProxySubject(RealSubject realSubject) {
        this.realSubject = realSubject;
    }
    private RealSubject realSubject;
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object returnObject=null;
        System.out.println("before");
        try{
             returnObject = method.invoke(realSubject, args);
        }catch (Exception e) {
            System.out.println("ex:"+e.getMessage());
            throw e;
        }finally {
            System.out.println("finally!");
        }
        return returnObject;
    }

    public static void main(String[] args) {
        IRealSubject subject = (IRealSubject)Proxy.newProxyInstance(
                JdkProxySubject.class.getClassLoader(),
                new Class[]{IRealSubject.class},
                new JdkProxySubject(new RealSubject())
        );
        subject.sayHi();
    }
}
